<?php
namespace app\lib\wechat;
use think\Exception;
/**
 * Prpcrypt class
 *
 * 提供接收和推送给公众平台消息的加解密接口.
 */
class Prpcrypt
{
    private $key = '';
    function __construct($key) {
        $this->key= base64_decode($key . "=");
    }

    public function encrypt($input)
    {
//        $data = openssl_encrypt($input, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->hex_iv));
//        $data = base64_encode($data);
//        return $data;
    }

    public function decrypt($encrypted,$appid)
    {
        try {
            $iv = substr($this->key, 0, 16);
            $ciphertext_dec = base64_decode($encrypted);
            $decrypted = openssl_decrypt($ciphertext_dec, 'aes-256-cbc', $this->key, OPENSSL_RAW_DATA, $iv);
        } catch (Exception $e) {
            return array(ErrorCode::$DecryptAESError, null);
        }
        try {
        $content = substr($decrypted, 16, strlen($decrypted));
        $len_list = unpack("N", substr($content, 0, 4));
        $xml_len = $len_list[1];
        $rxml = substr($content, 4, $xml_len);
        } catch (Exception $e) {
            //print $e;
            return array(ErrorCode::$IllegalBuffer, null);
        }
        return array(0, $rxml);
    }

    /*

      For PKCS7 padding

     */

    private function addpadding($string, $blocksize = 16) {
        $len = strlen($string);
        $pad = $blocksize - ($len % $blocksize);
        $string .= str_repeat(chr($pad), $pad);
        return $string;
    }

    private function strippadding($string) {
        $slast = ord(substr($string, -1));
        $slastc = chr($slast);
        $pcheck = substr($string, -$slast);
        if (preg_match("/$slastc{" . $slast . "}/", $string)) {
            $string = substr($string, 0, strlen($string) - $slast);
            return $string;
        } else {
            return false;
        }
    }

    function hexToStr($hex)
    {
        $string='';
        for ($i=0; $i < strlen($hex)-1; $i+=2)
        {
            $string .= chr(hexdec($hex[$i].$hex[$i+1]));
        }
        return $string;
    }
}
